package com.vichat.business.controller;

import com.vichat.business.entity.CommonAlarm;
import com.vichat.business.entity.DistrictFence;
import com.vichat.business.entity.DistrictFenceRule;
import com.vichat.business.entity.DistrictFenceUser;
import com.vichat.business.service.IDistrictFenceService;
import com.vichat.business.service.IVcAlarmService;
import com.vichat.business.vo.FenceVO;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.signal.CmdUtil;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.user.controller.BaseController;
import com.vichat.user.entity.SystemMessage;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.entity.UserOrg;
import com.vichat.user.entity.UserPartyCompany;
import com.vichat.user.service.ISystemMessageService;
import com.vichat.user.service.IUserService;
import com.vichat.user.vo.UserBasicVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ranjx on 2017/11/20.
 */
@Controller
@RequestMapping("/vcapi/fence")
public class DistrictFenceController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(DistrictFenceController.class);

    ExecutorService tp = Executors.newCachedThreadPool();

    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private IDistrictFenceService districtFenceService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IVcAlarmService vcAlarmService;
    @Autowired
    private ISystemMessageService systemMessageService;

    @RequestMapping("/createFence")
    @ResponseBody
    public Json createFence(@RequestBody FenceVO fenceVO) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            fenceVO.getDistrictFence().setPartyId(sessionUser.getPartyId());
            districtFenceService.saveFence(fenceVO);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 创建围栏
     *
     * @return
     */
    @RequestMapping("/saveFence")
    @ResponseBody
    public Json saveFence(@RequestBody DistrictFence districtFence) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            districtFenceService.saveDistrictFence(districtFence);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 创建围栏限制用户
     *
     * @return
     */
    @RequestMapping("/saveFenceUser")
    @ResponseBody
    public Json saveFenceUser(@RequestBody DistrictFenceUser queryBean) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            DistrictFence fenceFDB = districtFenceService.queryDistrictFenceByfenceId(sessionUser.getPartyId(), queryBean.getFenceId());
            if (fenceFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                if (queryBean.getIds() != null && !queryBean.getIds().isEmpty()) {
                    districtFenceService.saveDistrictFenceUser(sessionUser.getPartyId(), queryBean);
                    json.setSuccess(true);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 创建围栏规则
     *
     * @return
     */
    @RequestMapping("/saveFenceRule")
    @ResponseBody
    public Json saveFenceRole(@RequestBody DistrictFenceRule districtFenceRule) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            districtFenceService.saveDistrictFenceRule(sessionUser.getPartyId(), districtFenceRule);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 查询围栏
     *
     * @return
     */
    @RequestMapping("/queryFence")
    @ResponseBody
    public Grid queryFence(@RequestBody DistrictFence districtFence, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            //只能查到自己所在企业的围栏信息
            districtFence.setPartyId(sessionUser.getPartyId());

            List<DistrictFence> fences = districtFenceService.queryDistrictFences(districtFence, pageFilter);
            long count = districtFenceService.countDistrictFences(districtFence);

            grid.setData(fences);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 查询围栏
     *
     * @return
     */
    @RequestMapping("/queryFenceUser")
    @ResponseBody
    public Grid queryFenceUser(@RequestBody DistrictFenceUser districtFenceUser, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();

            List<DistrictFenceUser> fences = districtFenceService.queryDistrictFenceUsers(districtFenceUser, pageFilter);

            if (fences != null) {
                for (DistrictFenceUser fenceUser : fences) {
                    if (NumberUtils.isNotNullOrZero(fenceUser.getUserId()) && fenceUser.getType() == GlobalConstant.FENCE_USER_TYPE_PARTY) {
                        UserPartyCompany userParty = userService.getUserPartyCompanyByPartyId(fenceUser.getUserId());
                        if (userParty != null) {
                            fenceUser.setName(userParty.getCompanyName());
                        }
                        continue;
                    }
                    if (NumberUtils.isNotNullOrZero(fenceUser.getUserId()) && fenceUser.getType() == GlobalConstant.FENCE_USER_TYPE_ORG) {
                        UserOrg userOrg = userService.queryUserOrgByOrgId(fenceUser.getUserId());
                        if (userOrg != null) {
                            fenceUser.setName(userOrg.getOrgName());
                        }
                        continue;
                    }
                    if (NumberUtils.isNotNullOrZero(fenceUser.getUserId()) && (fenceUser.getType() == GlobalConstant.FENCE_USER_TYPE_USER || fenceUser.getType() == GlobalConstant.FENCE_USER_TYPE_SENDUSER)) {
                        UserBasic userBasic = userService.queryUserBasicByUid(fenceUser.getUserId());
                        UserOrg userOrg = userService.queryUserOrgByOrgId(userBasic.getOrgId());
                        if (userBasic != null) {
                            fenceUser.setName(userBasic.getUserName());
                            fenceUser.setOrgName(userOrg.getOrgName());
                        }
                        continue;
                    }
                }
            }

            long count = districtFenceService.countDistrictFenceUsers(districtFenceUser);

            grid.setData(fences);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 查询围栏
     *
     * @return
     */
    @RequestMapping("/queryFenceRule")
    @ResponseBody
    public Grid queryFenceRule(@RequestBody DistrictFenceRule districtFenceRule, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();

            List<DistrictFenceRule> fences = districtFenceService.queryDistrictFenceRules(districtFenceRule, pageFilter);
            long count = districtFenceService.countDistrictFenceRules(districtFenceRule);

            grid.setData(fences);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 删除围栏
     *
     * @return
     */
    @RequestMapping("/deleteFence")
    @ResponseBody
    public Json deleteFence(@RequestBody DistrictFence districtFence) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            if (sessionUser.getPartyId().longValue() == districtFence.getPartyId().longValue()) {
                districtFenceService.deleteFence(districtFence.getFenceId());

                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除围栏用户
     *
     * @return
     */
    @RequestMapping("/deleteFenceUser")
    @ResponseBody
    public Json deleteFenceUser(@RequestBody List<DistrictFenceUser> districtFenceUserList) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            for (DistrictFenceUser districtFenceUser : districtFenceUserList) {

                DistrictFence fenceFDB = districtFenceService.queryDistrictFenceByfenceId(sessionUser.getPartyId(), districtFenceUser.getFenceId());
                if (fenceFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                    districtFenceService.deleteFenceUser(sessionUser.getPartyId(), districtFenceUser.getFenceId(), districtFenceUser.getUserId(), districtFenceUser.getType());
                    json.setSuccess(true);
                }
            }
            districtFenceService.updateFenceUserRedis(sessionUser.getPartyId(), districtFenceUserList.get(0).getFenceId());
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除围栏规则
     *
     * @return
     */
    @RequestMapping("/deleteFenceRule")
    @ResponseBody
    public Json deleteFenceRule(@RequestBody DistrictFenceRule districtFenceRule) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();

            DistrictFence fenceFDB = districtFenceService.queryDistrictFenceByfenceId(sessionUser.getPartyId(), districtFenceRule.getFenceId());
            if (fenceFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                districtFenceService.deleteFenceRule(sessionUser.getPartyId(), districtFenceRule.getRuleId());
                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 查询告警信息
     *
     * @return
     */
    @RequestMapping("/queryAlarm")
    @ResponseBody
    public Grid queryCommonAlarm(@RequestBody CommonAlarm queryBean, PageFilter pf) {
        Grid grid = new Grid();
        try {
            UserBasic userBasic = getSessionUser();
            queryBean.setPartyId(userBasic.getPartyId());

            List<CommonAlarm> commonAlarms = vcAlarmService.queryCommonAlarms(queryBean, pf);

            if (commonAlarms != null && !commonAlarms.isEmpty()) {
                for (CommonAlarm alarm : commonAlarms) {
                    String uName = RedisHelper.getUname(alarm.getUid());
                    alarm.setuName(uName);
                    if (NumberUtils.isNotNullOrZero(alarm.getDealUid())) {
                        UserBasic userBasicFDB = userService.getUserBasicByUid(alarm.getDealUid());
                        if (userBasicFDB != null) {
                            alarm.setDealUName(userBasicFDB.getUserName());
                        }
                    }

                    if(alarm.getObjType() == DistrictFence.FENCE_TYPE_ENTER && alarm.getObjType() == DistrictFence.FENCE_TYPE_EXIT){
                        DistrictFence districtFence = districtFenceService.getDistrictFenceByfenceId(alarm.getObjId());
                        if(districtFence != null){
                            alarm.setObjName(districtFence.getFenceName());
                        }
                    }
                }
            }
            Long count = vcAlarmService.countCommonAlarms(queryBean);
            grid.setData(commonAlarms);
            grid.setCount(count);
        } catch (Exception e) {
            logger.error(e.getMessage());
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 处理告警
     *
     * @return
     */
    @RequestMapping("/dealAlarm")
    @ResponseBody
    public Json dealAlarm(CommonAlarm queryBean) {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
                throw new Exception("partyId不能为空");
            }
            if (queryBean.getPartyId().longValue() == userBasic.getPartyId().longValue()) {

                CommonAlarm queryBeanFDB = null;
                if (NumberUtils.isNotNullOrZero(queryBean.getAlarmId())) {
                    queryBeanFDB = vcAlarmService.getCommonAlarmByalarmId(queryBean.getAlarmId(), 1L);
                } else if (NumberUtils.isNotNullOrZero(userBasic.getUid())) {
                    queryBeanFDB = vcAlarmService.getCommonAlarmByalarmId(userBasic.getUid(), 1L);
                }

                if (queryBeanFDB != null) {
                    //开始处理告警
                    queryBeanFDB.setAlarmState(queryBean.getAlarmState());
                    queryBeanFDB.setDealTime(new Date());
                    queryBeanFDB.setDealUid(userBasic.getUid());
                    CommonAlarm alarm = vcAlarmService.saveCommonAlarm(queryBeanFDB);

                    CmdUtil.sendImMsg(10000, alarm.getUid(), 0, GlobalConstant.IMS_ALARM_CLOSE, "");
                }
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 保存
     *
     * @return
     */
    @RequestMapping("/saveDealResult")
    @ResponseBody
    public Json saveDealResult(Long alarmId, String dealResult) {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            CommonAlarm vcAlarm = vcAlarmService.getCommonAlarmByalarmId(alarmId);
            if (userBasic.getPartyId().longValue() == vcAlarm.getPartyId().longValue()) {
                vcAlarmService.saveDealResult(alarmId, dealResult);
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 关闭告警
     *
     * @return
     */
    @RequestMapping("/delAlarm")
    @ResponseBody
    public Json delAlarm(@RequestBody CommonAlarm queryBean) {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
                throw new Exception("partyId不能为空");
            }
            if(queryBean.getAlarmIds() != null) {
                for (long  alarmId :queryBean.getAlarmIds()) {
                    if (queryBean.getPartyId().longValue() == userBasic.getPartyId().longValue()) {
                        vcAlarmService.delCommonAlarm(alarmId);
                    }
                }
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/queryUserBasicToRoom")
    @ResponseBody
    public Grid queryUserBasicToRoom(UserBasic queryBean) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            queryBean.setPartyId(sessionUser.getPartyId());

            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            queryBean.setDisplayState(null);

            String userType = null;
            if(!StringUtils.isNotBlank(queryBean.getQueryUserType()) && !GlobalConstant.SUPPORT_ADMIN_LOGIN_APP){
                queryBean.setQueryUserType("3,4");
            }
            List<UserBasicVO> users = userService.queryUserBasicToRoom(queryBean,PageFilter.getMaxPageFilter(),queryBean.getQueryUserType());
            Long count = userService.countUserBasicToRoom(queryBean).longValue();
            grid.setData(users);
            grid.setCount(count);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/querySystemMessage")
    @ResponseBody
    public Grid querySystemMessage(SystemMessage queryBean, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            List<SystemMessage> systemMessages = systemMessageService.querySystemMessage(queryBean,pageFilter);
            if(systemMessages != null){
                for (SystemMessage message : systemMessages){
                    String userName = RedisHelper.getUname(message.getUid());
                    message.setName(userName);
                    message.setMsgJson(null);
                }
            }
            Long count = systemMessageService.countSystemMessage(queryBean).longValue();
            grid.setData(systemMessages);
            grid.setCount(count);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(-9);
        }
        return grid;
    }
}
